package com.csdj.controller;

import com.alibaba.fastjson.JSON;
import com.csdj.entity.DevUser;
import com.csdj.service.RedisService;
import com.csdj.service.UserService;
import com.csdj.utils.RandomUtil;
import com.csdj.utils.RedisUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Http接口-Controller
 */
@Controller
@RequestMapping("/game")
public class DevUserController {
    private Logger log = Logger.getLogger("DevUserController");
    @Resource
    UserService userService;
    @Resource
    RedisService redisService;

    @GetMapping("/login")
    public String login(){
        //int i = 1/0;
        return "devlogin";
    }
    @GetMapping("/logout")
    public String loginOut(){
        return "devlogin";//注销登录
    }

    @GetMapping("toMain")
    public String toMain(){
        return "/developer/main";
    }

    @PostMapping("/main")
    public String login(@RequestParam String devCode, @RequestParam String devPassword, Model model,
                        HttpServletRequest request, HttpSession session, HttpServletResponse response) {
        log.info("doLogin");
        DevUser devUser  = userService.login(devCode, devPassword);

        session = request.getSession();
        if (devUser != null) {
            session.setAttribute("user",devUser);
            model.addAttribute("name",devCode);

            session.setAttribute("id",devUser.getId());
            int max=1000000000,min=1;
            int ran2 = (int) (Math.random()*(max-min)+min);
            String bd = Integer.toString(ran2)+Integer.toString(devUser.getId());
            redisService.hset("users",bd, Integer.toString(ran2));
            //创建Cookie对象
            Cookie c1=new Cookie("uid", Integer.toString(devUser.getId()));
            Cookie c2=new Cookie("token", Integer.toString(ran2));
            //设置Cookie的有效期(3天)
            c1.setMaxAge(120);
            c2.setMaxAge(120);
            response.addCookie(c1);
            response.addCookie(c2);

            String strUser = JSON.toJSONString(devUser);

            Integer userTypeId = devUser.getUserType();
            if(userTypeId!=1){
                return "backend/main";
            }

        } else {
            System.err.println("密码错误");
            return "/devlogin";
        }
        return "/developer/main";
    }

    @GetMapping("/appinfoadd")
    public String appinfoadd(){

        return "developer/appinfoadd";
    }
}
